﻿//创建人：longb
//日期：2022-04-25
//描述：物料配送管理
var page = {
    rootPath: getRootPath(), //网站根路径
    ajaxUrl: getRootPath() + "/Ashx/ZsHandler/ZSSendRequestHandler.ashx",
    editIndex: null, //easyUI单元格编辑
    //初始化页面
    init: function () {
        page.bind();
        page.addEditCell();
    },
    addEditCell: function () //给easyuigrid新增editcell方法
    {
        $.extend($.fn.datagrid.methods, {
            editCell: function (jq, param) {
                return jq.each(function () {
                    var opts = $(this).datagrid('options');
                    var fields = $(this).datagrid('getColumnFields', true).concat($(this).datagrid('getColumnFields'));
                    for (var i = 0; i < fields.length; i++) {
                        var col = $(this).datagrid('getColumnOption', fields[i]);
                        col.editor1 = col.editor;
                        if (fields[i] != param.field) {
                            col.editor = null;
                        }
                    }
                    $(this).datagrid('beginEdit', param.index);
                    for (var i = 0; i < fields.length; i++) {
                        var col = $(this).datagrid('getColumnOption', fields[i]);
                        col.editor = col.editor1;
                    }
                });
            }
        });
    },
    endEditing: function (gridId) {
        if (page.editIndex == undefined) { return true }
        if ($('#' + gridId).datagrid('validateRow', page.editIndex)) {
            $('#' + gridId).datagrid('endEdit', page.editIndex);
            page.editIndex = undefined;
            return true;
        } else {
            return false;
        }
    },
    //页面事件绑定
    bind: function () {
        $('#OrderType').combobox({
            data: [{ id: 1, text: '正常' }, { id: 0, text: '临时'}],
            valueField: 'id',
            textField: 'text'
        });
        $('#PsType').combobox({
            data: [{ id: 1, text: '正常' }, { id: 2, text: '临时'}],
            valueField: 'id',
            textField: 'text'
        });
        $('#OrderStatus').combobox({
            data: [{ id: 0, text: '待接收' }, { id: 5, text: '已接收' }, { id: 10, text: '配送中' }, { id: 15, text: '配送完' }, { id: 20, text: '收料完成' }, { id: 999, text: '全部'}],
            valueField: 'id',
            textField: 'text',
            onSelect: function (record) {
                if (record.id != 0) {
                    $('#ReciveSend').linkbutton("disable"); //禁止接收按钮
                } else {
                    $('#ReciveSend').linkbutton("enable"); //.attr("onclick", "page.ReciveSend()");
                }
                if (record.id != 10 && record.id != 5) {
                    $('#StartSend').linkbutton("disable"); //禁止配送按钮
                    $('#SaveERPData').linkbutton("disable");
                } else {
                    $('#StartSend').linkbutton("enable"); //.attr("onclick", "page.StartSend()"); 
                    $('#SaveERPData').linkbutton("enable");
                }

            }
        });
        $('#OrderType').combobox('setValue', 1);
        $('#PsType').combobox('setValue', 1);
        $('#OrderStatus').combobox('setValue', 0);
        $('#OrderTabel').datagrid({
            checkOnSelect: false,
            selectOnCheck: false,
            singleSelect: true,
            columns: [[
               { field: 'ck', title: '选择', checkbox: true },
                 { field: 'ATTRIBUTEVALUE', title: '发动机号', width: 120 },
                 { field: 'MFGORDERNAME', title: '订单号', width: 150 },
		         { field: 'TOGETHERFLAG', title: '任务单号', width: 180 },
		         { field: 'WORKFLOWTYPE', title: '任务类型', width: 90, align: 'center' },
                 { field: 'PRODUCTNAME', title: '件号', width: 120 },
                 { field: 'DESCRIPTION', title: '件号名称', width: 90 },
                 { field: 'WORKFLOWSTEPNAME', title: '阶段', width: 100 },
                 { field: 'WFDESC', title: '工艺名称', width: 120 },
                 { field: 'STEPNAME', title: '工序名称', width: 120 },
                 { field: 'PLANNEDSTARTDATE', title: '计划开始时间', width: 130 },
                 { field: 'PLANNEDFINISHDATE', title: '计划完成时间', width: 130 },
                 { field: 'APPLYTYPE', title: '配送提请类型', width: 100, align: 'center' },
                 { field: 'STATUS', title: '任务状态', width: 100, align: 'center' }
                ]],
            onSelect: function (index, row) {
                page.GetAuxMaterialData();
                $("#OrderTabel").datagrid("uncheckAll").datagrid("checkRow", index);
            },
            onCheckAll: function (rows) {
                $("#OrderTabel").datagrid("clearSelections");
            },
            onCheck: function (rowIndex, rowData) {
                var checkRows = $("#OrderTabel").datagrid("getChecked");
                var selectRow = $("#OrderTabel").datagrid("getSelected");
                if (checkRows.length > 1) {
                    $("#OrderTabel").datagrid("clearSelections");
                }
            }
        });
        $('#AuxMaterialTabel').datagrid({
            checkOnSelect: false,
            selectOnCheck: false,
            singleSelect: true,
            onClickCell: function (index, field, value) {
                //编辑单元格
                if (page.endEditing('AuxMaterialTabel')) {
                    var row = $('#AuxMaterialTabel').datagrid('getRows')[index];
                    if (field == 'EDITORQTY' && value > 0 && row.PRODUCTBATCHNO != null && row.PREPAREQTY != null) {
                        $('#AuxMaterialTabel').datagrid('editCell', { index: index, field: field });
                        page.editIndex = index;
                    }
                    if (field == 'PRODUCTBATCHNO' || field == 'PREPAREQTY') {
                        $('#AuxMaterialTabel').datagrid('editCell', { index: index, field: field });
                        page.editIndex = index;
                    }
                }
            },
            columns: [[
		        { field: 'AUXMATERIALNAME', title: '材料编码', width: 100 },
		        { field: 'DESCRIPTION', title: '材料描述', width: 100 },
                { field: 'SPECIFICATION', title: '型号规格', width: 100 },
                { field: 'RESOURCETYPENAME', title: '材料类型', width: 100 },
		        { field: 'QTY', title: '需求数量', width: 100, align: 'center' },
                { field: 'PRODUCTBATCHNO', title: '批次号', width: 100, align: 'center', editor: 'textbox', styler: function () { return 'background-color:#f8f8f8;color:red'; } },
                { field: 'PREPAREQTY', title: '已装备数量', width: 100, align: 'center', editor: 'numberbox', styler: function () { return 'background-color:#f8f8f8;color:red'; } },
                { field: 'NOPREPAREQTY', title: '未准备数量', width: 100, align: 'center', formatter: function (value, row, index) { var qty = row.QTY - row.PREPAREQTY; if (qty > 0) { return qty; } else { return 0; } } },
                { field: 'EDITORQTY', title: '本次配送数量', width: 100, align: 'center', editor: 'numberbox', styler: function () { return 'background-color:#f8f8f8;color:red'; } },
                { field: 'SENDQTY', title: '已配送量', width: 100, hidden: true },
                { field: 'NOSENDQTY', title: '未配送量', width: 100, align: 'center', formatter: function (value, row, index) { return row.QTY - row.SENDQTY; } },
                { field: 'OUTSTORETIME', title: '出库时间', width: 100 },
                { field: 'PRODUCTDESC', title: '有效期至', width: 100 }
                ]],
            onAfterEdit: function (index, row, changes) {
                if (row.QTY < Number(changes.EDITORQTY) + Number(row.SENDQTY)) { displayMessage("材料【" + row.DESCRIPTION + "】本次配送数量+已配送量>需求数量", false); }
            },
            onLoadSuccess: function (data) {
                var status = $('#OrderStatus').combobox('getValue');
                var isExist = data.rows.some(function (i) {
                    return i.PRODUCTBATCHNO === null || i.PREPAREQTY === null
                })
                if (!isExist && (status == 5 || status == 10)) {
                    $('#StartSend').linkbutton("enable");
                } else {
                    $('#StartSend').linkbutton("disable");
                }
            }
        });
        $('#ReciveSend').click(function () {
            page.ReciveAuxMaterialSend();
        });
        $('#StartSend').click(function () {
            page.StartAuxMaterialSend();
        });
        $('#SaveERPData').click(function () {
            page.SaveERPData();
        });
    },
    //查询
    searchData: function () {
        clearMessage();
        $('#AuxMaterialTabel').datagrid('loadData', []);
        page.GetZsRequiredTools();
    },
    //查询重置
    searchReset: function () {
        $('#searchForm').form('clear');
        page.bind();
        clearMessage();
    },
    //查询任务单信息
    GetZsRequiredTools: function () {
        $('#AuxMaterialTabel').datagrid('loadData', [])
        var frdata = $('#searchForm').serializeArray();
        var data = {};
        $.each(frdata, function () {
            data[this.name] = this.value
        });
        var param = {
            action: "GetZsRequiredTools",
            TransportType: "3",
            data: JSON.stringify([data])
        };
        page.post(param, function (res) {
            $('#OrderTabel').datagrid('loadData', res.DBTable);
        });
    },
    //获取材料信息
    GetAuxMaterialData: function () {
        var row = $('#OrderTabel').datagrid('getSelected');
            var param = {
                action: "GetAuxMaterialData",
                TransportType: "3",
                workflowstepid: row.WORKFLOWSTEPID,
                ContainerNo: row.TOGETHERFLAG,
                ID: row.ZSREQUIREDTOOLSTRANSPORTID
            };
            page.post(param, function (res) {
                $('#AuxMaterialTabel').datagrid('loadData', res.DBTable);
            });
    },
    //接收配送提请
    ReciveAuxMaterialSend: function () {
        var rows = $('#OrderTabel').datagrid('getChecked');
        if (rows.length == 0) {
            displayMessage("请勾选任务单信息，再进行操作");
            return;
        }
        var param = {
            action: "ReciveToolsSend",
            TransportType: "3",
            data: JSON.stringify(rows)
        };
        page.post(param, function (res) {
            if (res.Result) {
                page.GetZsRequiredTools();
            }
            displayMessage(res.Message, res.Result);
        });

    },
    //开始配送
    StartAuxMaterialSend: function () {
        var row = $('#OrderTabel').datagrid('getSelected');
        var AuxMaterial = $('#AuxMaterialTabel').datagrid('getRows');
        if (AuxMaterial.length == 0) { return; }
        var data = [];
        $.each(AuxMaterial, function (index, item) {
            if (item.EDITORQTY > 0) {
                data.push(item);
            }
        });
        if (data.length == 0) {
            displayMessage("订单所需材料已配送完");
            return;
        }
        var param = {
            action: "StartToolsSend",
            workflowstepid: row.WORKFLOWSTEPID,
            EnginepartplanID: row.ENGINEPARTPLANID,
            APPLYTYPE: row.APPLYTYPE == "临时" ? "2" : "1",
            TransportType: "3",
            data: JSON.stringify(data)
        };
        page.post(param, function (res) {
            if (res.Result) {
                //page.GetAuxMaterialData();
                page.GetZsRequiredTools();
                $('#AuxMaterialTabel').datagrid('loadData', []);
            }
            displayMessage(res.Message, res.Result);
        });
    },
    SaveERPData: function () {
        var tools = $('#AuxMaterialTabel').datagrid('getRows');
        if (tools.length==0) { return; }
        var param = {
            action: "SaveERPData",
            data: JSON.stringify(tools)
        }
        page.post(param, function (res) {
            if (res.Result) {
                page.GetAuxMaterialData();
            }
            displayMessage(res.Message, res.Result);
        });
    },
    //清除方法，重要！！！
    reset: function (iscondition, isresult) {
        clearMessage();
    },

    //post数据
    post: function (param, callback) {
        $.ajax({
            type: "Post",
            url: page.ajaxUrl,
            data: param,
            cashe: false,
            async: true,
            dataType: "json",
            beforeSend: function () {
                $.messager.progress({ text: '', msg: '处理中...' });
            },
            success: function (data) {
                $.messager.progress('close');
                callback(data);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $.messager.progress('close');
                displayMessage(XMLHttpRequest.responseText, false);
            }
        });
    }
}
$(function () {
    page.init();
});